import { HOME_URL } from '@/config'
export function getUrlVariable(variable: string) {
  const query = window.location.search.substring(1)
  const vars = query.split('&')
  for (let i = 0; i < vars.length; i++) {
    const pair = vars[i].split('=')
    if (pair[0] === variable) {
      return pair[1]
    }
  }
  return ''
}

function trimStr(str: string, char: string) {
  const reg = new RegExp(`^${char}+|${char}+$`, 'g')
  return str.replace(reg, '')
}

export function resetUri() {
  const context = trimStr(import.meta.env.VITE_PUBLIC_PATH, '/')
  const home = trimStr(HOME_URL, '/')
  let url = window.location.protocol + '//' + window.location.host + '/' + context + '/' + home
  if (url.indexOf('?') !== -1) {
    // 判断是否存在参数
    url = url.replace(/(\?|#)[^'"]*/, '') // 去除参数
  }
  window.location.href = url
}

// export function resetUri() {
//   let url = window.location.href // 获取当前页面的url
//   if (url.indexOf('?') !== -1) {
//     //判断是否存在参数
//     url = url.replace(/(\?|#)[^'"]*/, '') // 去除参数
//     window.history.replaceState({}, '', url)
//   }
// }

export function getIndex(path: string) {
  if (path.indexOf('?') !== -1) {
    //判断是否存在参数
    path = path.replace(/(\?|#)[^'"]*/, '') // 去除参数
  }
  return path
}

export function toPortal(redirect?: boolean) {
  let LOGIN_URL = import.meta.env.VITE_LOGIN_URL
  if (!LOGIN_URL.startsWith('http')) {
    LOGIN_URL = window.location.protocol + '//' + window.location.host + LOGIN_URL
  }
  if (redirect) {
    LOGIN_URL = LOGIN_URL + '?redirect_uri=' + window.location.href
  }
  window.location.replace(LOGIN_URL)
}
